package com.hubujun.driverlicense.core;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;

public class Trigger extends Handler {

	/**
	 * 当前序列号的值
	 */
	private static int _globalId;
	/**
	 * 此序号检查器的值
	 */
	private int id;

	public boolean isContinue;
	/**
	 * 超时时间
	 */
	public long timeout;

	private final TriggerExecutor executor;

	public Trigger(Looper looper, TriggerExecutor exe, boolean isConti) {
		super(looper == null ? Looper.getMainLooper() : looper);
		timeout = 0L;
		executor = exe;
		init();
		isContinue = isConti;
	}

	public Trigger(TriggerExecutor exe, boolean isConti) {
		timeout = 0L;
		executor = exe;
		init();
		isContinue = isConti;
	}
	
	private void init(){
		if (_globalId >= 8192)
			_globalId = 0;
		int i = 1 + _globalId;
		_globalId = i;
		id = i;
	}

	public final void cancel() {
		removeMessages(id);
	}

	/**
	 * 设置超时检查的时间
	 * 
	 * @param time
	 */
	public void delayed(long time) {
		timeout = time;
		cancel();
		sendEmptyMessageDelayed(id, time);
	}

	public boolean b() {
		return !hasMessages(id);
	}

	protected void finalize() {
		cancel();
	}

	public void handleMessage(Message message) {
		if (message.what == id && executor != null && executor.execute() && isContinue)
			sendEmptyMessageDelayed(id, timeout);
	}
}
